//
//  LoginViewController.m
//  xpkc
//
//  Created by wanmeizty on 14-8-18.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "LoginViewController.h"
#import "MBProgressHUD.h"
@interface LoginViewController ()

@end

@implementation LoginViewController{
    AFHTTPRequestOperationManager *manager;
    LoginView *loginView;
    UIImage *img;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatView];
}
- (void)viewWillAppear:(BOOL)animated{
    [self.navigationController.navigationBar setTranslucent:YES];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_clear"] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewWillDisappear:(BOOL)animated{
    [self.navigationController.navigationBar setTranslucent:NO];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_green"] forBarMetrics:UIBarMetricsDefault];
    [manager.operationQueue cancelAllOperations];
}

/**
 *  创建视图
 */
-(void)creatView{
    UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(0, -64, SCREEN_WIDTH, SCREEN_HEIGHT+64)];
    bg.backgroundColor = GreenColor;
    [self.view addSubview:bg];
    //登录界面
    loginView = [[LoginView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT)];
    loginView.delegate = self;
    [bg addSubview:loginView];
    
    manager = [AFHTTPRequestOperationManager manager];
}


#pragma mark - loginview delegate
- (void)loginWithUsername:(NSString *)username andPassword:(NSString *)password{
//    NSString *module = @"userLogin";
//    NSString *interface = @"loginfo";
//    
//    NSString *timeString = [GetTime getTime];
//    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
//    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL,module,interface,hashString];
//    
//    NSDictionary *parameter = @{@"time":timeString,@"userName":username,@"userPWD":[password md5]};
//         [[NSUserDefaults standardUserDefaults]setValue:username forKey:USERNAME_REMBER];
//    [[NSUserDefaults standardUserDefaults]setValue:password forKey:PASSWORD_REMBER];
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.labelText = @"登录中";
//
//     manager = [AFHTTPRequestOperationManager manager];
//    //密码记得MD5加密一下
//     manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        //完成
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
//        /**
//         *  判断发送请求的格式是否正确，不正确的话返回的参数是比较蛋疼的
//         */
//        if ([dic objectForKey:@"timerror"]) {
//            logdebug(@"faterror:退出登录");
//            [UserMessage sharedUserMessage].isLogin = NO;
//            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确保手机时间与北京时间相差五分钟以内" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
//            [alert show];
//            return ;
//        }
//        int success = [[dic objectForKey:@"succ"]intValue];
//        if (success) {
//            //登录成功
//            //记录登录成功的用户的设备类型和当前版本
//            //            //设备类型
//            //            NSString *strModel  = [UIDevice currentDevice].model;
//            //            logdebug(@"%@",strModel);
//            //            //当前系统版本
//            //            NSString *syslVersion = [[UIDevice currentDevice] systemVersion];
//            //            logdebug(@"%@",sysVersion);
//            //成功
//            [loginView loginStatue:LoginStatueSucc];
//            NSDictionary *data = [dic objectForKey:@"data"];
//            NSString *mid = [data objectForKey:@"mid"];
//            NSString *userid = [data objectForKey:@"userid"];
//            NSString *headimg = [data objectForKey:@"face"];
//            logdebug(@"%@",data);
//            logdebug(@"\nNo.%@\nUserName:%@\n  [登录成功]",mid,userid);
//            //保存登录信息
//            [UserMessage sharedUserMessage].isLogin = YES;
//            [UserMessage sharedUserMessage].userId = [data objectForKey:@"userid"];//用户名
//            [UserMessage sharedUserMessage].userMid = [data objectForKey:@"mid"];//数字
//            [[NSUserDefaults standardUserDefaults] setValue:[UserMessage sharedUserMessage].userMid forKey:USERMID_REMBER];
//            [[NSUserDefaults standardUserDefaults] setValue:[UserMessage sharedUserMessage].userId forKey:USERNAME_REMBER];
//            [[NSUserDefaults standardUserDefaults] setValue:headimg forKey:USERHEAD_REMBER];
//            [[NSUserDefaults standardUserDefaults] synchronize];//记录usermid
//            [self viewWillAppear:YES];
//        }
//        int errorPWD = [[dic objectForKey:@"errorPwd"]intValue];
//        if (errorPWD) {
//            //密码错误
//            [loginView loginStatue:LoginStatuePasswordError];
//        }
//        int errorAcc = [[dic objectForKey:@"errorAcc"]intValue];
//        if (errorAcc) {
//            //用户名错误
//            [loginView loginStatue:LoginStatueUsernameError];
//        }
//        [hud hide:YES];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        ShowAlertMsg(@"请求超时，请检查网络并重新登录");
//        [loginView loginStatue:LoginStatueInternetError];
//        [hud hide:YES];
//    }];


    
    NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
    NSString *string = [NSString stringWithFormat:@"/Login/login/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
    NSString *MD5string = [string md5];
    NSString *urlString = [NSString stringWithFormat:@"http://www.studypay.com/MAPI/index.php/Login/login/hash/%@/appid/1", MD5string];
    //密码记得MD5加密一下
    NSDictionary *paramters = [NSDictionary dictionaryWithObjectsAndKeys:username,@"userName",[password md5],@"userPWD",timeString,@"time", nil];
    [[NSUserDefaults standardUserDefaults]setValue:username forKey:USERNAME_REMBER];
    [[NSUserDefaults standardUserDefaults]setValue:password forKey:PASSWORD_REMBER];
    
    
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:paramters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //完成
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        /**
         *  判断发送请求的格式是否正确，不正确的话返回的参数是比较蛋疼的
         */
        if ([dic objectForKey:@"timerror"]) {
            logdebug(@"faterror:退出登录");
            [UserMessage sharedUserMessage].isLogin = NO;
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请确保手机时间与北京时间相差五分钟以内" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            return ;
        }
        int success = [[dic objectForKey:@"succ"]intValue];
        if (success) {
            //登录成功
            //记录登录成功的用户的设备类型和当前版本
            //            //设备类型
            //            NSString *strModel  = [UIDevice currentDevice].model;
            //            logdebug(@"%@",strModel);
            //            //当前系统版本
            //            NSString *syslVersion = [[UIDevice currentDevice] systemVersion];
            //            logdebug(@"%@",sysVersion);
            //成功
            [loginView loginStatue:LoginStatueSucc];
            NSDictionary *data = [dic objectForKey:@"data"];
            NSString *mid = [data objectForKey:@"mid"];
            NSString *userid = [data objectForKey:@"userid"];
            logdebug(@"\nNo.%@\nUserName:%@\n  [登录成功]",mid,userid);
            //保存登录信息
            [UserMessage sharedUserMessage].isLogin = YES;
            [UserMessage sharedUserMessage].userId = [data objectForKey:@"userid"];//用户名
            [UserMessage sharedUserMessage].userMid = [data objectForKey:@"mid"];//数字
            [[NSUserDefaults standardUserDefaults] setValue:[UserMessage sharedUserMessage].userMid forKey:USERMID_REMBER];
              [[NSUserDefaults standardUserDefaults]setValue:password forKey:PASSWORD_REMBER];
            [[NSUserDefaults standardUserDefaults] setValue:[data objectForKey:@"face"] forKey:USERHEAD_REMBER];
            [[NSUserDefaults standardUserDefaults] synchronize];//记录usermid
            [self viewWillAppear:YES];
            self.loginBlock(username,username);
            [self.navigationController popViewControllerAnimated:YES];
        }
        int errorPWD = [[dic objectForKey:@"errorPwd"]intValue];
        if (errorPWD) {
            //密码错误
            [loginView loginStatue:LoginStatuePasswordError];
        }
        int errorAcc = [[dic objectForKey:@"errorAcc"]intValue];
        if (errorAcc) {
            //用户名错误
            [loginView loginStatue:LoginStatueUsernameError];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        ShowAlertMsg(@"请求超时，请检查网络并重新登录");
        [loginView loginStatue:LoginStatueInternetError];
    }];
}
- (void)regist{
    RegistViewController *RVC = [[RegistViewController alloc]init];
    RVC.title = @"注册学派网账号";
    RVC.delegate = self;
    [self.navigationController pushViewController:RVC animated:YES];
}
- (void)forgot{
    RetrieveViewController *RVC = [[RetrieveViewController alloc]init];
    RVC.title = @"密码找回";
    [self.navigationController pushViewController:RVC animated:YES];
}
- (void)remember:(UIButton *)btn{
    if (btn.selected) {
        logdebug(@"记住密码");
        btn.selected = NO;//记住
        [[NSUserDefaults standardUserDefaults]setValue:@"YES" forKey:USER_REMBER];
    }else{
        logdebug(@"不记密码");
        btn.selected = YES;
        [[NSUserDefaults standardUserDefaults]setValue:@"NO" forKey:USER_REMBER];
    }
}
- (void)fillUserName:(NSString *)username andPassWord:(NSString *)password{
    [loginView fillUsername:username andPassword:password];
}

#pragma mark - other
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
